from PySide import QtGui, QtCore
from gencodeform_ui import Ui_Form
import sys
sys.path.append('..')
from mol.fm_parser import exact_mass

class GenCodeForm(QtGui.QWidget, Ui_Form):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.setupUi(self)
        self.lineEdit.setValidator(
                QtGui.QRegExpValidator(QtCore.QRegExp(r'([1-9][0-9]*\.{,1}[0-9]*,{,1})*'), self.lineEdit))
        self.lineEdit_2.setValidator(
                QtGui.QRegExpValidator(
                    QtCore.QRegExp(r'([A-Z][a-zA-Z0-9]*:{,1}-{,1}[0-9]{,2},{,1})*'), self.lineEdit_2))

        self.pushButton.clicked.connect(self._reset_line_edits)
        self.pushButton_2.clicked.connect(self._get_diagnostic_ion_mzs)

    def _get_mzs(self):
        txt = self.lineEdit.text().encode('utf8')
        if txt != '':
            return [float(i) for i in txt.strip().split(',')]
        return []

    def _get_fms(self):
        txt = self.lineEdit_2.text().encode('utf8')
        if txt != '':
            tmpl = []
            for i in txt.strip().split(','):
                if not i.split(':')[0]: continue
                if not ':' in i or i.endswith(':') or i.endswith('-'):
                    tmpl.append((i.split(':')[0], 0))
                else:
                    l = i.split(':')
                    tmpl.append((l[0], int(l[1])))
            return tmpl
        return []

    def _reset_line_edits(self):
        self.lineEdit.setText('')
        self.lineEdit_2.setText('')

    def _get_diagnostic_ion_mzs(self):
        tmpl = []
        chg = 0
        for fm, chg in self._get_fms():
            print fm, chg
            tmpl.append(exact_mass(fm, chg))
        print tmpl + self._get_mzs()
        return tmpl + self._get_mzs()

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    w = GenCodeForm()
    w.show()
    sys.exit(app.exec_())
